import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, notification, Cascader, Row, Col } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import { DICT } from '../enum';

import TrimInput, { withTrim } from '@/components/TrimInput'
import { DividerItem } from '@/components/DividerItem';
import { DropDownSelectObj } from '@/components/DropDownSelect';
import { fomatter } from '@/utils/formatter';

const TextArea = withTrim(Input.TextArea);

interface Props extends FormComponentProps {
  dispatch?: Function,
  brand?: any,
  location?: any;
  lBrand?: any,
  lLocation: any,
  key: any,
  data?: {
    id: any,
    buildId?: any,
    floorId?: any,
    areaId?: any,
    brandId?: any,
    productId?: any,
    floorPlanX?: any,
    floorPlanY?: any,
    brandName?: string,
    productName?: string,
    buildName?: string, floorName?: string, areaName?: string,
    fire?: string;
  },
  keys?: Array<string>,
  dict?: object;
}

@connect(({ device_fire_monitor, loading }) => ({
  locationData: device_fire_monitor.locationData || {},
  optionData: device_fire_monitor.optionData || {},
  brand: device_fire_monitor.brand || [], // BRAND
  dict: device_fire_monitor.dict || [], // BRAND
  lBrand: loading.effects['device_fire_monitor/queryBrand'],
  location: device_fire_monitor.location || [],
  lLocation: loading.effects['device_fire_monitor/queryLocation']
}))
class FormItem extends Component<Props, any> {
  readonly state = {

  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;
    dispatch({
      type: 'device_fire_monitor/init', payload: {
        dict: { keyList: DICT },
      }
    })
    if (data && data.id) {
      const {
        brandId, productId,
        buildId, floorId, areaId,
        buildName, floorName, areaName,
        brandName, productName,
        ...res
      } = data;

      form.setFieldsValue({
        ...res,
        fire: '700190030',
      })
    } else {
      form.setFieldsValue({
        fire: '700190030',
      })
    }

  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form, data, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {

        const res = FOMMATER.map(v => fomatter(
          values[v.list],
          data ? v.names.map(u => data[u]) : null,
          v.len,
          v.names
        ))

        const flag = FOMMATER.every(v => !!v);
        if (!flag) {
          notification['error']({
            message: `保存失败`,
            description: '信息录入不规范',
          });
          return;
        }

        let params = {
          ...values,
        }

        delete params.systemNo

        res.forEach(v => {
          params = {
            ...v,
            ...params,
          }
        })

        data && data.id ? dispatch({
          type: 'device_fire_monitor/update',
          payload: {
            id: data.id,
            ...params
          }
        }) : dispatch({
          type: 'device_fire_monitor/create',
          payload: params
        })
      } else {
        notification['error']({
          message: `${data.id ? '修改' : '创建'}失败`,
          description: '字段验证不通过',
        });
      }
    })
  };


  loadData = (type, selectedOptions) => {
    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `device_fire_monitor/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  render() {
    const { form, data, dict = {} } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 12, offset: 0 },
        sm: { span: 13, offset: 4 },
      },
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 13 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 1,
        },
      },
    };
    const iconName = data && data.id ? 'edit' : 'plus'
    const Header = DividerItem(iconName, '火焰识别摄像头');


    return (
      <>
        <Header />
        <Form onSubmit={this.handleSubmit}>
          <Row>
            <Col span={12}>
              {/* {data && data.id &&
                <Form.Item
                  {...formItemLayout}
                  label="系统编号"
                >
                  {getFieldDecorator('systemNo', {
                    rules: [{
                      required: true, message: '系统编号',
                    }],
                  })(
                    <TrimInput placeholder='请输入系统编号'  disabled />
                  )}
                </Form.Item>
              } */}
              <Form.Item
                {...formItemLayout}
                label="设备名称"
              >
                {getFieldDecorator('name', {
                  rules: [{
                    required: true, message: '设备名称',
                  }],
                })(
                  <TrimInput placeholder='请输入设备名称' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label='安装地址'
                required
              >
                {getFieldDecorator('buildList')(
                  <Cascader
                    // disabled={!!(data && data.id)}
                    options={this.props.location}
                    loadData={this.loadData.bind(this, 'queryLocation')}
                    changeOnSelect={this.props.lLocation}
                    placeholder={data ? `${data.buildName || ''}${data.floorName || ''}${data.areaName || ''}` : '请选择'}
                  />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayoutWithOutLabel}
              >
                {getFieldDecorator('installationAddr', {
                  rules: [{
                    required: false, message: '请输入详细地址',
                  }],
                })(
                  <TextArea rows={3} placeholder='请输入详细地址' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="通讯地址"
              >
                {getFieldDecorator('networkAddr', {
                  rules: [{
                    required: true, message: '通讯地址',
                  }],
                })(
                  <TrimInput placeholder='请输入通讯地址' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="S/N码"
              >
                {getFieldDecorator('serialNumber', {
                  rules: [{
                    required: false, message: 'S/N码',
                  }],
                })(
                  <TrimInput placeholder='请输入S/N码' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label='检查类型'
              >
                {getFieldDecorator('fire', {
                  rules: [{ required: true, message: '检查类型' }],
                })(
                  (DropDownSelectObj({ dict, type: 'device.fire', disabled: true, onChange: () => { } }))
                )}
              </Form.Item>

              <Form.Item
                {...formItemLayout}
                label='厂家型号'
                required
              >
                {getFieldDecorator('brandList', {
                  rules: [{ required: false }],
                })(
                  <Cascader
                    options={this.props.brand}
                    loadData={this.loadData.bind(this, 'queryBrand')}
                    changeOnSelect={this.props.lBrand}
                    placeholder={data && data.id ? `${data.brandName || ''}${data.productName || ''}` : '请选择'}
                  />
                )}
              </Form.Item>

              <Form.Item {...tailFormItemLayout} style={{ marginTop: 91 }}>
                <Button onClick={() => {
                  window.history.back()
                }}>取消
              </Button>
                <Button style={{ marginLeft: '5%' }} type="primary" htmlType="submit">保存</Button>
              </Form.Item>
            </Col>
            <Col span={12} >
              <Form.Item
                {...formItemLayout}
                label="实时镜像名称"
              >
                {getFieldDecorator('cameraName', {
                  rules: [{
                    required: false, message: '实时镜像名称',
                  }],
                })(
                  <TrimInput placeholder='请输入实时镜像名称' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="实时镜像地址"
              >
                {getFieldDecorator('cameraAddress', {
                  rules: [{
                    required: false, message: '实时镜像地址',
                  }],
                })(
                  <TrimInput placeholder='请输入实时镜像地址' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="热成像名称"
              >
                {getFieldDecorator('thermalImageName', {
                  rules: [{
                    required: false, message: '热成像名称',
                  }],
                })(
                  <TrimInput placeholder='请输入热成像名称' />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="热成像地址"
              >
                {getFieldDecorator('thermalImageAddress', {
                  rules: [{
                    required: false, message: '热成像地址',
                  }],
                })(
                  <TrimInput placeholder='请输入热成像地址' />
                )}
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;


const FOMMATER = [{
  names: ['buildId', 'floorId', 'areaId'],
  list: 'buildList',
  len: 2
}, {
  names: ['brandId', 'productId'],
  list: 'brandList',
  len: 2
}]